import { GoogleGenAI, Type } from "@google/genai";
import { v4 as uuidv4 } from 'uuid';


// Environment Configuration
const API_KEY = process.env.API_KEY;
const AI_PROVIDER = process.env.AI_PROVIDER || 'openai'; // 'gemini' | 'openai'
const AI_MODEL = process.env.AI_MODEL || (AI_PROVIDER === 'openai' ? 'deepseek-v3.1' : 'gemini-2.5-flash');
const AI_BASE_URL = process.env.AI_BASE_URL || 'https://api.modelarts-maas.com/v2';

const JUDGE_COUNT = parseInt(process.env.JUDGE_COUNT || '5', 10);
const SINGLE_CHOICE_COUNT = parseInt(process.env.SINGLE_CHOICE_COUNT || '5', 10);
const MULTI_CHOICE_COUNT = parseInt(process.env.MULTI_CHOICE_COUNT || '5', 10);
const TOTAL_COUNT = JUDGE_COUNT + SINGLE_CHOICE_COUNT + MULTI_CHOICE_COUNT;


const generatePrompt = (topic) => `
请生成一份关于"${topic}"的综合考试试卷。
试卷必须包含以下三种题型：单选题 (Single Choice)、多选题 (Multiple Choice) 和 判断题 (True/False)。
题目数量：总共${TOTAL_COUNT}道题, 判断题(${JUDGE_COUNT}道)、单选题(${SINGLE_CHOICE_COUNT}道) 和 多选题(${MULTI_CHOICE_COUNT}道)
输出语言必须为：简体中文 (Simplified Chinese)。

返回格式必须是合法的 JSON，结构如下:
{
  "title": "试卷标题",
  "description": "试卷描述",
  "questions": [
    {
      "id": "q1",
      "type": "choice" 或 "judge",
      "title": "题目内容",
      "options": ["选项A", "选项B"], (仅选择题需要)
      "correctAnswer": "答案", (单选/判断为字符串 "A" 或 "true"，多选为 JSON 数组字符串 '["A","B"]')
      "explanation": "答案解析",
      "hint": "提示"
    }
  ]
}
`;

const generatePromptFromQuestions = (questions) => `
用户在以下题目中犯了错误，请根据这些题目涉及的知识点，生成一份新的综合考试试卷，旨在帮助用户巩固薄弱环节。
错题列表：
${questions.map((q, i) => `${i+1}. [${q.type}] ${q.title}`).join('\n')}

试卷必须包含以下三种题型：单选题 (Single Choice)、多选题 (Multiple Choice) 和 判断题 (True/False)。
题目数量：总共${TOTAL_COUNT}道题, 判断题(${JUDGE_COUNT}道)、单选题(${SINGLE_CHOICE_COUNT}道) 和 多选题(${MULTI_CHOICE_COUNT}道)
输出语言必须为：简体中文 (Simplified Chinese)。

返回格式必须是合法的 JSON，结构如下:
{
  "title": "试卷标题",
  "description": "根据您的错题生成的强化练习卷",
  "questions": [
    {
      "id": "q1",
      "type": "choice" 或 "judge",
      "title": "题目内容",
      "options": ["选项A", "选项B"], (仅选择题需要)
      "correctAnswer": "答案", (单选/判断为字符串 "A" 或 "true"，多选为 JSON 数组字符串 '["A","B"]')
      "explanation": "答案解析",
      "hint": "提示"
    }
  ]
}
`;

// --- Gemini Implementation ---
const generateWithGemini = async (topic, isMistakeMode = false) => {
  const ai = new GoogleGenAI({ apiKey: API_KEY });

  const responseSchema = {
    type: Type.OBJECT,
    properties: {
      title: { type: Type.STRING, description: "试卷标题" },
      description: { type: Type.STRING, description: "试卷简短描述" },
      questions: {
        type: Type.ARRAY,
        items: {
          type: Type.OBJECT,
          properties: {
            id: { type: Type.STRING, description: "题目ID (e.g. q1, q2)" },
            type: { type: Type.STRING, enum: ["choice", "judge"], description: "题目类型" },
            title: { type: Type.STRING, description: "题目文本" },
            options: {
              type: Type.ARRAY,
              items: { type: Type.STRING },
              description: "选项列表 (选择题必填)"
            },
            correctAnswer: {
              type: Type.STRING,
              description: "正确答案。单选/判断题为 'A' 或 'true'。多选题为 JSON 字符串，例如 '[\"A\", \"B\"]'。"
            },
            explanation: { type: Type.STRING, description: "答案解析" },
            hint: { type: Type.STRING, description: "提示 (可选)" }
          },
          required: ["id", "type", "title", "correctAnswer", "explanation"]
        }
      }
    },
    required: ["title", "questions"]
  };

  const prompt = isMistakeMode ? generatePromptFromQuestions(topic) : generatePrompt(topic);
  const response = await ai.models.generateContent({
    model: AI_MODEL,
    contents: prompt,
    config: {
      responseMimeType: "application/json",
      responseSchema: responseSchema,
      systemInstruction: `你是一位专业的出题专家。请生成高质量、有挑战性的中文试题。
      确保 'correctAnswer' 字段格式正确:
      - 单选或判断题: 直接返回字符串 (例如 "A", "true", "false")。
      - 多选题: 返回字符串化的 JSON 数组 (例如 '["A", "B"]' )。`,
    },
  });

  const text = response.text;
  if (!text) throw new Error("未生成内容");
  return parseAndFormatQuiz(JSON.parse(text));
};


// --- OpenAI Implementation ---
const generateWithOpenAI = async (topic, isMistakeMode = false) => {

  // return testData();
  if (!API_KEY) throw new Error("Missing API Key");

  const response = await fetch(`${AI_BASE_URL}/chat/completions`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${API_KEY}`
    },
    body: JSON.stringify({
      model: AI_MODEL,
      messages: [
        {
          role: "system",
          content: `你是一位专业的出题专家。请生成 JSON 格式的中文试题。
          正确答案(correctAnswer)格式要求:
          - 单选/判断: 字符串 (如 "A", "true")
          - 多选: JSON数组字符串 (如 "[\"A\", \"B\"]")`
        },
        {
          role: "user",
          content: (isMistakeMode ? generatePromptFromQuestions(topic) : generatePrompt(topic)) + "\n请直接返回 JSON 数据，不要包含 Markdown 格式化符号。"
        }
      ],
      response_format: { type: "json_object" }
    })
  });

  if (!response.ok) {
    const err = await response.text();
    console.error("OpenAI API Error:", err);
    throw new Error(`OpenAI request failed: ${response.statusText}`);
  }

  const data = await response.json();
  console.log(JSON.stringify(data));
  const content = data.choices[0]?.message?.content;
  if (!content) throw new Error("No content from OpenAI");

  return parseAndFormatQuiz(JSON.parse(content));
};

// --- Common Parser ---
const parseAndFormatQuiz = (data) => {
  const processedQuestions = data.questions.map((q) => {
    let processedAnswer = q.correctAnswer;
    
    // Generate new UUID for each question
    const newId = uuidv4();

    // Attempt to parse if it looks like a JSON array string for multi-choice
    if (typeof processedAnswer === 'string') {
      const trimmed = processedAnswer.trim();
      // If it looks like an array, try to parse
      if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
        try {
          processedAnswer = JSON.parse(trimmed);
        } catch (e) {
          // keep as string if parse fails
        }
      }
    }

    // Normalization for Judge type
    if (q.type === 'judge') {
      if (processedAnswer === true || processedAnswer === 'True' || processedAnswer === '正确') processedAnswer = 'true';
      if (processedAnswer === false || processedAnswer === 'False' || processedAnswer === '错误') processedAnswer = 'false';
    }

    // Normalize type to 'choice' for single/multiple
    let processedType = q.type;
    if (processedType === 'multiple' || processedType === 'single') {
      processedType = 'choice';
    }

    return { ...q, id: newId, type: processedType, correctAnswer: processedAnswer };
  }).filter(q => q.type === 'choice' || q.type === 'judge');

  // Sort questions: Judge -> Single Choice -> Multi Choice
  processedQuestions.sort((a, b) => {
    const getWeight = (q) => {
      if (q.type === 'judge') return 0;
      if (q.type === 'choice') {
        // If answer is array, it's multi-choice (weight 2)
        // If answer is string, it's single-choice (weight 1)
        return Array.isArray(q.correctAnswer) ? 2 : 1;
      }
      return 3; // Unknown types last
    };
    return getWeight(a) - getWeight(b);
  });

  return {
    id: Date.now().toString(),
    title: data.title,
    description: data.description || `关于 ${data.title} 的测试`,
    questions: processedQuestions,
    createdAt: Date.now(),
  };
}

// --- Main Export ---
export const generateQuiz = async (topic) => {
  try {
    console.log(`Generating quiz with provider: ${AI_PROVIDER}`);
    if (AI_PROVIDER === 'openai') {
      return await generateWithOpenAI(topic, false);
    } else {
      return await generateWithGemini(topic, false);
    }
  } catch (error) {
    console.error("Quiz generation error:", error);
    throw error;
  }
};

export const generateQuizFromMistakes = async (questions) => {
  try {
    console.log(`Generating quiz from mistakes with provider: ${AI_PROVIDER}`);
    // Limit questions to avoid token limits (e.g., take last 20)
    const limitedQuestions = questions.slice(0, 20);
    
    if (AI_PROVIDER === 'openai') {
      return await generateWithOpenAI(limitedQuestions, true);
    } else {
      return await generateWithGemini(limitedQuestions, true);
    }
  } catch (error) {
    console.error("Quiz generation from mistakes error:", error);
    throw error;
  }
};














const testData = () => {
  return parseAndFormatQuiz({
    "title": "自考英语综合能力测试",
    "description": "本试卷涵盖英语语法、词汇、阅读理解和基础语言知识，适用于自学考试英语科目备考练习",
    "questions": [
      {
        "id": "q1",
        "type": "choice",
        "title": "下列哪个选项是'enthusiastic'的正确中文释义？",
        "options": [
          "热情的",
          "冷漠的",
          "犹豫的",
          "悲伤的"
        ],
        "correctAnswer": "A",
        "explanation": "enthusiastic意为热情的、热心的，是积极的情感表达",
        "hint": "注意词根enthusiasm的含义"
      },
      {
        "id": "q2",
        "type": "choice",
        "title": "If I _____ enough money, I would buy a new computer.",
        "options": [
          "have",
          "had",
          "will have",
          "having"
        ],
        "correctAnswer": "B",
        "explanation": "这是虚拟语气结构，表示与现在事实相反的假设，故用过去式had",
        "hint": "注意虚拟语气的时态使用规则"
      },
      {
        "id": "q3",
        "type": "choice",
        "title": "选择正确的被动语态形式：The novel _____ by many readers.",
        "options": [
          "is enjoyed",
          "enjoyed",
          "enjoys",
          "enjoying"
        ],
        "correctAnswer": "A",
        "explanation": "被动语态结构为be+过去分词，主语novel是动作的承受者",
        "hint": "注意主谓关系和语态选择"
      },
      {
        "id": "q4",
        "type": "choice",
        "title": "She speaks English _____ her mother.",
        "options": [
          "as fluent as",
          "more fluent than",
          "as fluently as",
          "fluently than"
        ],
        "correctAnswer": "C",
        "explanation": "修饰动词speaks应该用副词fluently，同级比较用as...as结构",
        "hint": "注意副词比较级的用法"
      },
      {
        "id": "q5",
        "type": "choice",
        "title": "By the time we arrived, the meeting _____.",
        "options": [
          "had already begun",
          "already began",
          "has already begun",
          "was beginning"
        ],
        "correctAnswer": "A",
        "explanation": "过去完成时表示在过去某个时间点之前已经完成的动作",
        "hint": "注意时间状语by the time引导的时态搭配"
      },
      {
        "id": "q6",
        "type": "choice",
        "title": "He suggested that we _____ early to avoid traffic.",
        "options": [
          "start",
          "started",
          "would start",
          "starting"
        ],
        "correctAnswer": "A",
        "explanation": "suggest后接宾语从句时，从句谓语用should+动词原形，should可省略",
        "hint": "注意表示建议的动词后的从句用法"
      },
      {
        "id": "q7",
        "type": "choice",
        "title": "The teacher asked the students _____ talking.",
        "options": [
          "stop",
          "to stop",
          "stopping",
          "stopped"
        ],
        "correctAnswer": "B",
        "explanation": "ask sb to do sth是 固定搭配，表示要求某人做某事",
        "hint": "注意动词ask的用法搭配"
      },
      {
        "id": "q8",
        "type": "choice",
        "title": "This is the house _____ I was born.",
        "options": [
          "which",
          "that",
          "where",
          "when"
        ],
        "correctAnswer": "C",
        "explanation": "where引导定语从句，在 从句中作地点状语",
        "hint": "注意关系副词where的用法"
      },
      {
        "id": "q9",
        "type": "choice",
        "title": "If it _____ tomorrow, we will cancel the picnic.",
        "options": [
          "rains",
          "will rain",
          "rained",
          "is raining"
        ],
        "correctAnswer": "A",
        "explanation": "在条件 状语从句中，用一般现在时表示将来",
        "hint": "注意条件句中的时态规则"
      },
      {
        "id": "q10",
        "type": "choice",
        "title": "She is not only a good teacher _____ a kind friend.",
        "options": [
          "but also",
          "and",
          "or",
          "nor"
        ],
        "correctAnswer": "A",
        "explanation": "not only...but also是固定搭配，表示不仅...而且",
        "hint": "注意关联连词的搭配使用"
      },
      {
        "id": "q11",
        "type": "multiple",
        "title": "下列哪些是情态动词？",
        "options": [
          "can",
          "should",
          "go",
          "make",
          "must"
        ],
        "correctAnswer": "[\"A\", \"B\", \"E\"]",
        "explanation": "can、should、must都是情态动词，后接动词原形",
        "hint": "情态动词表示能力、许可、义务等含义"
      },
      {
        "id": "q12",
        "type": "multiple",
        "title": "下列哪些时态表示将来时间？",
        "options": [
          "will do",
          "am doing",
          "have done",
          "am going to do",
          "did"
        ],
        "correctAnswer": "[\"A\", \"B\", \"D\"]",
        "explanation": "will do、现在进行时表安排、be going to do都可以表示将来",
        "hint": "英语中有多种方式表达将来时"
      },
      {
        "id": "q13",
        "type": "multiple",
        "title": "下列哪些词是不可数名词？",
        "options": [
          "water",
          "book",
          "information",
          "student",
          "advice"
        ],
        "correctAnswer": "[\"A\", \"C\", \"E\"]",
        "explanation": "water、information、advice都是不可 数名词，没有复数形式",
        "hint": "不可数名词不能与a/an连用，没有复数形式"
      },
      {
        "id": "q14",
        "type": "multiple",
        "title": "下列哪些是复合句的连接词？",
        "options": [
          "although",
          "and",
          "because",
          "but",
          "so"
        ],
        "correctAnswer": "[\"A\", \"C\"]",
        "explanation": "although和because是从属连词，引导状语从句",
        "hint": "注意区分并列连词和从属连词"
      },
      {
        "id": "q15",
        "type": "multiple",
        "title": "下列哪些是英语中的冠词？",
        "options": [
          "a",
          "the",
          "an",
          "some",
          "any"
        ],
        "correctAnswer": "[\"A\", \"B\", \"C\"]",
        "explanation": "a、an是不定冠词，the是定冠词",
        "hint": "冠词用于限定名词"
      },
      {
        "id": "q16",
        "type": "multiple",
        "title": "下列哪些动词后接动名词作宾语？",
        "options": [
          "enjoy",
          "want",
          "finish",
          "decide",
          "avoid"
        ],
        "correctAnswer": "[\"A\", \"C\", \"E\"]",
        "explanation": "enjoy、finish、avoid等动词后接动名词作宾语",
        "hint": "记住常接动名词作宾语的动词"
      },
      {
        "id": "q17",
        "type": "multiple",
        "title": "下列哪些是反身代词？",
        "options": [
          "myself",
          "your",
          "himself",
          "them",
          "ourselves"
        ],
        "correctAnswer": "[\"A\", \"C\", \"E\"]",
        "explanation": "myself、himself、ourselves都是反身代词",
        "hint": "反身代词表示动作返回到执行者本身"
      },
      {
        "id": "q18",
        "type": "multiple",
        "title": "下列哪些是条件句的类型？",
        "options": [
          "zero conditional",
          "first conditional",
          "past conditional",
          "future conditional",
          "mixed conditional"
        ],
        "correctAnswer": "[\"A\", \"B\", \"E\"]",
        "explanation": "零条件句、第一条件句和混合条件句都是常见的条件句类型",
        "hint": "条件句根据真实性和时间不同分类"
      },
      {
        "id": "q19",
        "type": "multiple",
        "title": "下列哪些是英语中的元音字母？",
        "options": [
          "a",
          "b",
          "e",
          "i",
          "o"
        ],
        "correctAnswer": "[\"A\", \"C\", \"D\", \"E\"]",
        "explanation": "a、e、i、o是元音字母，u也是元音字母但未在选项中",
        "hint": "英语有5个元音字母：a、e、i、o、u"
      },
      {
        "id": "q20",
        "type": "multiple",
        "title": "下列哪些可以表示被动语态？",
        "options": [
          "be done",
          "get done",
          "have done",
          "make done",
          "let done"
        ],
        "correctAnswer": "[\"A\", \"B\"]",
        "explanation": "be done是标准被动式，get done是口语中常用的被动表达",
        "hint": "被动语态表示主语是动作的承受者"
      },
      {
        "id": "q21",
        "type": "judge",
        "title": "'She go to school every day.'这个句子语法正确。",
        "correctAnswer": "false",
        "explanation": "主语是第三人称单数，谓语动词应该用goes",
        "hint": "注意主谓一致原则"
      },
      {
        "id": "q22",
        "type": "judge",
        "title": "英语中形容词通常位于名词之前。",
        "correctAnswer": "true",
        "explanation": "英语形容词通常作定语时位于名词前，如a beautiful flower",
        "hint": "注意英语语序特点"
      },
      {
        "id": "q23",
        "type": "judge",
        "title": "'I have been to Beijing last year.'这个句子时态使用正确。",
        "correctAnswer": "false",
        "explanation": "last year是明确的过去时间状语，应该用一般过去时I went to Beijing last year",
        "hint": "注意时间状语与动词时态的搭配"
      },
      {
        "id": "q24",
        "type": "judge",
        "title": "英语中所有疑问 句都需要助动词。",
        "correctAnswer": "false",
        "explanation": "当疑问词作主语时，不需要助动词，如Who came here?",
        "hint": "注意特殊疑问句的语 序"
      },
      {
        "id": "q25",
        "type": "judge",
        "title": "'Neither of the answers is correct.'这个句子主谓一致正确。",
        "correctAnswer": "true",
        "explanation": "neither of后接复数名词时，谓语动词用单数形式",
        "hint": "注意不定代词的主谓一致"
      }
    ]
  })
}
